﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Crap4Net.Formatters.Crap4JFormatter
{
    struct HistogramEntry
    {
        public HistogramEntry(string binLabel, int value)
        {
            BinLabel = binLabel;
            BinValue = value;
        }
        public string BinLabel;
        public int BinValue;

        public override string ToString()
        {
            return BinLabel + ":" + BinValue;
        }
    }
    class HistogramCalculator
    {

        public static IList<HistogramEntry> EmptyHistogram
        {
            get
            {
                var empmtyHisogram = new List<HistogramEntry>();
                for (int i = 0; i < _labels.Length; i++)
                {
                    empmtyHisogram.Add(new HistogramEntry(_labels[i], 0));
                }
                return empmtyHisogram;
            }
        }


        static int[] _binValues = { 0, 1, 2, 4, 8, 16, 32, 64, 128, int.MaxValue };
        static string[]  _labels = { "one", "two", "four", "eight", "sixteen", "thirtytwo", "sixtyfour", "one28", "two56" };

        public IList<HistogramEntry> CalculateHistogram(IList<CombinedDataEntry> data)
        {
            var result = EmptyHistogram; 
            if (data==null)
                throw new ArgumentNullException("data cant be null");
            for (int i = 1; i < _binValues.Length; i++)
            {
                var numOfMethods = GetNumbersOfMethodsInBin(i, data);

                result[i - 1] = new HistogramEntry(_labels[i-1], numOfMethods);
            }
            return result;

        }
        private int GetNumbersOfMethodsInBin(int binIndex,IList<CombinedDataEntry> data)
        {
            var count = (from entry in data
                         where entry.Crap <= _binValues[binIndex] && entry.Crap > _binValues[binIndex-1]
                         select entry).Count();
            return count;
        }
    }
}
